package cn.codeartist.springboot.component.http;

import cn.codeartist.springboot.component.http.converter.FormHttpMessageConverter;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * Http组件
 *
 * @author 艾江南
 * @date 2019/4/19
 */
@Configuration
public class HttpAutoConfiguration {

    @Bean
    @Scope(BeanDefinition.SCOPE_PROTOTYPE)
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        List<HttpMessageConverter<?>> converters = new ArrayList<>();
        // 字符串转换器
        StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
        stringConverter.setDefaultCharset(UTF_8);
        stringConverter.setWriteAcceptCharset(false);
        converters.add(stringConverter);
        // Jackson转换器，使用下划线转小驼峰策略
        MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
        jsonConverter.setDefaultCharset(UTF_8);
        jsonConverter.getObjectMapper().setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
        converters.add(jsonConverter);
        // Form表单转换器
        converters.add(new FormHttpMessageConverter());
        return builder.messageConverters(converters).build();
    }
}
